<template>
  <div>
    <backHeader :pageTitle="movieData.name" />
    <div id="container" class="container" ref="container">
      <div
        style="width:100%;text-align: center;margin-top:10px; margin-bottom:10px;float:left;font-size:13px;"
        v-if="movieData == ''"
      >加载数据中...</div>
      <div :class="['player-box','player-box-'+ device]" ref="playerBox">
        <div id="video" style="width:100%;height:100%;"></div>
        <div class="clear"></div>
      </div>
      <div :class="['movie-msg','movie-msg-'+device]" ref="movieMsg">
        <ul>
          <li>
            <div v-if="device == 'web' ">影片信息</div>
            <div class="movie-msg-cover">
              <img :src="movieData.cover" :onerror="'this.src=\''+ errorCover+'\''" />
            </div>
            <div class="movie-msg-infomation">{{movieData.name}}</div>
            <div class="movie-msg-infomation">{{movieData.year}}</div>
            <div class="movie-msg-infomation">{{movieData.country}}、{{movieData.language}}</div>
            <div class="movie-msg-infomation">{{movieData.director | performerFormat}}</div>
            <div class="movie-msg-infomation">{{movieData.performer | performerFormat}}</div>
            <div
              class="movie-msg-infomation"
              :title="movieData.description"
            >{{movieData.description | descriptionFormat}}</div>
            <div class="clear"></div>
          </li>
        </ul>
      </div>
      <div :class="['play-list','play-list-'+device]" ref="playList">
        <ul>
          <li>
            <div>
              播放列表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;加载进度:{{videobuffer}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;播放源:
              <select @change="changeSource()">
                <option
                  v-for="(sourceItem,index) in currentPlayUris"
                  :key="index"
                  :value="index"
                  :selected="(index+1) == currentPlayUrlIndex"
                >{{index+1}}</option>
              </select>
            </div>
            <div v-if="device=='web'">
              <div class="vrmode" style="width:55px;" @click="toVr()">VR观看</div>
              <div class='vrmode' style="width:55px;" @click="toVr()">采集</div>
              <div class="clear"></div>
            </div>
            <div>
              <div
                :class="['play-index',{'play-index-default':!displayType}, {'selectActive':(item.index == currentIndex)}]"
                v-for="item in play_url_list"
                :key="item.index"
                @click="toPlay(item.index)"
                :title="item.name"
              >{{displayType?item.index:item.name}}</div>
              <div class="clear"></div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="clear"></div>
  </div>
</template>

<script>
import backHeader from "@/components/public/backHeader.vue";
import api from "@/lib/apis/movies.js";
import { size, sizeType } from "@/lib/getSize.js";
export default {
  data() {
    return {
      device: size.getDeviceType(),
      movieData: "",
      errorCover: require("@/assets/images/404.png"),
      play_url_list: [],
      displayType: false,
      //播放列表

      //播放器
      currentIndex: 0, //当前播放索引
      currentPlayUrl: "", //当前播放地址
      currentPlayUrlIndex: 0, //当前播放地址索引
      currentPlayUris: [], //当前索引地址集合
      currentPlayType: "",
      validState: false,
      metaData: "",
      videobuffer: 0,
      debug: true,
      playerControl: null, //播放器控件
      playerConfig: {
        playerID: "ckplayer1",
        container: "#video", //容器的ID或className
        variable: "player", //播放函数名称
        autoplay: false,
        loaded: "",
        poster: require("@/assets/images/player_box_background.jpg"), //封面图片
        video: {
          file: "",
          type: "video/m3u8"
        }
      }
    };
  },
  mounted() {
    this.initLayout();
    window.onresize = () => {
      this.initLayout();
    };
    this.getMovieData();
    this.getPlayUrls();
    this.$nextTick(() => {
      this.initPlayer();
    });
  },
  watch: {
    play_url_list(val) {
      let index = 1;
      if (this.$route.query.index != null) {
        index = this.$route.query.index;
      } else {
        var list = JSON.parse(localStorage.getItem("myhistory") || "[]");
        for (let i = 0; i < list.length; i++) {
          if (list[i].id == this.$route.query.movieId) {
            index = list[i].index;
          }
        }
      }
      this.toPlay(index);
    },
    currentPlayUrl(value) {
      this.videobuffer = 0;
      let val = value[1];
      if (this.currentPlayUrl != null) {
        /*检测视频类型*/
        let videoType = "";
        if (/^(http|https):\/\/.*?\.m3u8/gi.test(val)) {
          videoType = { type: "m3u8", playType: "video/m3u8" };
        } else if (
          /^(http|https):\/\/.*?\.(wmv|divx|xvid|mp4|3ivx|rgp|mov|3gp|m4a)/gi.test(
            val
          )
        ) {
          videoType = { type: "mp4", playType: "video/mp4" };
        } else if (/^(http|https):\/\/.*?\.mkv/gi.test(val)) {
          videoType = { type: "webm", playType: "video/webm" };
        } else if (/^(http|https):\/\/.*?\.ogg/gi.test(val)) {
          videoType = { type: "ogg", playType: "video/ogg" };
        }
        this.playerConfig.autoplay = true;
        this.playerConfig.video.file = val;
        //根据URL类型判断是否需要重新加载播放器切换播放类型.
        if (this.playerControl.playerType == "html5video") {
          if (this.playerConfig.video.type != videoType.playType) {
            this.playerControl.removeChild();
            this.playerConfig.video.type = videoType.playType;
            this.initPlayer();
          } else {
            this.playerControl.newVideo(this.playerConfig);
          }
        } else {
          if (this.playerConfig.video.type != videoType.playType) {
            this.playerConfig.video.type = videoType.playType;
            this.initPlayer();
          } else {
            this.playerControl.newVideo(this.playerConfig);
          }
        }
        // 监听播放链接是否有效,无效就轮询下一个.
        window.document.title =
          this.movieData.name + "【" + this.currentIndex + "】";
        var ret = setTimeout(() => {
          if (this.validState) {
            this.validVideo();
          } else {
            clearTimeout(ret);
          }
        }, 20000);
        /*保存观看历史*/
        // 处理本地缓存
        var m_history = {
          id: this.movieData.id,
          name: this.movieData.name,
          index: this.currentIndex
        };
        var list = JSON.parse(localStorage.getItem("myhistory") || "[]");
        var i = 0;
        if (list.length > 20) {
          list.pop();
        }
        for (i; i < list.length; i++) {
          if (list[i].id == m_history.id) {
            list[i].index = m_history.index;
            break;
          }
        }
        if (i >= list.length) {
          list.unshift(m_history);
        }
        localStorage.setItem("myhistory", JSON.stringify(list));
      }
    }
  },
  methods: {
    /*
      数据API
    */
    getMovieData() {
      let id = this.$route.query.movieId;
      if (id != null) {
        api
          .getMovieDetail(id)
          .then(response => {
            this.movieData = response.data;
            window.document.title = this.movieData.name;
            this.getdisplayType(this.movieData.category);
          })
          .catch(error => {
            //todo loading error
            console.log(error);
          });
      }
    },
    getdisplayType(id) {
      api
        .getCategory(id)
        .then(response => {
          this.displayType = response.data.display_index;
        })
        .catch(error => {
          this.displayType = false;
        });
    },
    getPlayUrls() {
      let id = this.$route.query.movieId;
      if (id != null) {
        api
          .getPlayList(id)
          .then(response => {
            var data = response.data;
            //处理播放地址（多源合一）
            let m_sources = 0;
            let m_index = 0;
            for (let i = 0; i < data.length; i++) {
              if (m_sources != data[i].sources) {
                m_sources = data[i].sources;
                m_index = 0;
              }
              m_index += 1;
              let movie_ret = {
                index: m_index,
                uri: data[i].play_url,
                name: data[i].p_index
              };
              if (movie_ret.index > this.play_url_list.length) {
                this.play_url_list.push({
                  index: movie_ret.index,
                  name: movie_ret.name,
                  uris: [movie_ret.uri]
                });
              } else {
                this.play_url_list[movie_ret.index - 1].uris.push(
                  movie_ret.uri
                );
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    /*
      播放器相关设置
    */

    initPlayer() {
      let flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      if (flag != null) {
        this.playerConfig.loaded = this.h5Addlisten;
        this.playerControl = new ckplayer(this.playerConfig);
      } else {
        this.playerConfig.loaded = "window.playerlisten";
        this.playerControl = new ckplayer(this.playerConfig);
        window.player = this.playerControl;
        window.setBuffer = this.bufferHandle;
        window.setDuration = this.duration;
        window.setEnd = this.playend;
        function endHandle() {
          window.endHandle();
        }
        window.endHandle = function() {
          window.setEnd();
        };
        function bufferHandle(buffer) {
          window.bufferHandle(buffer);
        }
        window.bufferHandle = function(buffer) {
          window.setBuffer(buffer);
        };
        function durationHandler(duration) {
          window.durationHandler();
        }
        window.durationHandler = function(duration) {
          window.setDuration(duration);
        };
        window.playerlisten = function() {
          window.player.addListener("ended", endHandle);
          window.player.addListener("buffer", bufferHandle);
          window.player.addListener("duration", durationHandler);
        };
      }
    },
    h5Addlisten() {
      this.playerControl.addListener("duration", this.duration);
      this.playerControl.addListener("ended", this.playend);
      this.playerControl.addListener("time", this.timeHandle); //兼容不能捕获 duration，buffer事件
      this.playerControl.addListener("buffer", this.bufferHandle);
    },
    timeHandle(time) {
      if (time > 0) {
        this.validState = false;
        this.videobuffer = 100;
      }
    },
    duration(val) {
      if (val > 0) {
        this.validState = false;
      }
    },
    bufferHandle(buffer) {
      this.videobuffer = buffer;
      if (buffer > 0) {
        this.validState = false;
      }
    },
    playend() {
      // 播放器播放完成监听.
      this.toPlay(this.currentIndex + 1);
    },
    changeSource(){
      // todo 更换源.
      this.playerNewVideo(event.srcElement.options[event.srcElement.selectedIndex].value)
    },
    validVideo() {
      let result = false;
      if (this.validState) {
        if (this.videobuffer > 0) {
          this.validState = false;
          result = true;
        }
      }
      if (!result) {
        this.playerNewVideo();
      }
    },
    toPlay(index) {
      //播放新视频.
      this.currentIndex = index; //播放成功
      this.currentPlayUrlIndex = 0;
      this.metaData = "";
      if (this.currentIndex <= this.play_url_list.length) {
        //获取播放地址集.
        this.currentPlayUris = this.play_url_list[this.currentIndex - 1].uris;
        this.playerNewVideo();
      } else {
        alert("已经播放完毕.");
      }
    },
    playerNewVideo(index = -1) {
      this.validState = true;
      if (index == -1) {
          this.currentPlayUrlIndex += 1;
        } else {
          this.currentPlayUrlIndex = index;
        }
      if (this.currentPlayUrlIndex <= this.currentPlayUris.length) {
        let url = this.currentPlayUris[this.currentPlayUrlIndex-1];
        /*处理播放地址*/
        if (/^(http|https):\/\/.*?\.(m3u8|mp4|avi|mov|mpg|mpeg)/gi.test(url)) {
          this.currentPlayUrl = [this.currentPlayUrlIndex, url];
        } else {
          api
            .getM3U8File(url)
            .then(response => {
              this.currentPlayUrl = [
                this.currentPlayUrlIndex,
                response.data["m3u8"]
              ];
            })
            .catch(error => {
              console.log(error);
            });
        }
      } else {
        this.validState = false;
        alert("播放失败.");
      }
    },
    toVr(){
      this.$router.push({ path: 'vr', query: { uri: this.currentPlayUrl[1] }})
    },
    /*
      布局相关
    */
    initLayout() {
      //初始化容器.
      this.device = size.getDeviceType();
      let rectSize = size.GET(sizeType.document);
      this.$refs.container.style.width = rectSize.width + "px";
      this.$refs.container.style.height = rectSize.height - 40 + "px";
      this.$refs.container.style.marginTop = "40px";
      this.watchLayout();
    },
    watchLayout() {
      //布局计算.
      let rectSize = size.GET(sizeType.element, this.$refs.container);
      switch (this.device) {
        case "web": {
          //todo web layout
          this.$refs.playerBox.style.width = rectSize.width * 0.6 + "px";
          this.$refs.movieMsg.style.width = rectSize.width * 0.2 + "px";
          this.$refs.playList.style.width = rectSize.width * 0.2 + "px";
          this.$refs.playerBox.style.height = rectSize.height + "px";
          this.$refs.movieMsg.style.height = rectSize.height + "px";
          this.$refs.playList.style.height = rectSize.height + "px";
          this.$refs.playerBox.style.marginLeft = rectSize.width * 0.2 + "px";
          this.$refs.movieMsg.style.marginLeft = "0px;";
          this.$refs.playList.style.marginLeft = rectSize.width * 0.8 + "px";
          break;
        }
        case "pad": {
          //todo pad layout
          this.$refs.playerBox.style.width = rectSize.width + "px";
          this.$refs.movieMsg.style.width = rectSize.width - 10 + "px";
          this.$refs.playList.style.width = rectSize.width - 20 + "px";

          this.$refs.playerBox.style.height = rectSize.height * 0.5 + "px";
          this.$refs.movieMsg.style.height = "auto";
          this.$refs.playList.style.height = "auto";

          this.$refs.playerBox.style.marginLeft = "0px";
          this.$refs.movieMsg.style.marginLeft = "10px;";
          this.$refs.playList.style.marginLeft = "10px";
          this.$refs.playerBox.style.marginTop = "40px;";
          var marginTopPos = 10;
          this.$refs.movieMsg.style.marginTop = marginTopPos + "px";
          this.$refs.playList.style.marginTop = marginTopPos + "px";
          break;
        }
        case "phone": {
          //todo phone layout
          this.$refs.playerBox.style.width = rectSize.width + "px";
          this.$refs.movieMsg.style.width = rectSize.width - 10 + "px";
          this.$refs.playList.style.width = rectSize.width - 20 + "px";

          this.$refs.playerBox.style.height = rectSize.height * 0.3 + "px";
          this.$refs.movieMsg.style.height = "auto";
          this.$refs.playList.style.height = "auto";

          this.$refs.playerBox.style.marginLeft = "0px";
          this.$refs.movieMsg.style.marginLeft = "10px;";
          this.$refs.playList.style.marginLeft = "10px";
          this.$refs.playerBox.style.marginTop = "40px;";
          var marginTopPos = 10;
          this.$refs.movieMsg.style.marginTop = marginTopPos + "px";
          this.$refs.playList.style.marginTop = marginTopPos + "px";
          break;
        }
      }
    }
  },
  filters: {
    descriptionFormat(value) {
      //格式化详细介绍.
      let n =
        size.getDeviceType() == "web"
          ? 180
          : size.getDeviceType() == "pad"
          ? 80
          : 40;
      if (value) {
        if (value.length > n) {
          return value.substring(0, n) + "...";
        } else {
          return value;
        }
      }
    },
    performerFormat(value) {
      let n =
        size.getDeviceType() == "web"
          ? 180
          : size.getDeviceType() == "pad"
          ? 13
          : 13;
      if (value) {
        if (value.length > n) {
          return value.substring(0, n) + "...";
        } else {
          return value;
        }
      }
    }
  },
  components: {
    backHeader
  }
};
</script>

<style scoped>
/*player-box*/
.player-box {
  background-color: #000000;
  margin: auto;
}

.player-box-web {
  position: absolute;
}
.player-box-pad {
  width: 100%;
}
.player-box-phone {
  width: 100%;
}

/*movie-msg*/
.movie-msg {
  width: 100%;
}
.movie-msg-web {
  position: absolute;
  text-align: center;
}

.movie-msg-web ul {
  list-style: none;
  margin: 0px;
  padding: 0px;
}
.movie-msg-web ul li {
  text-align: center;
  padding-left: 10px;
}
.movie-msg-web ul li div {
  margin: auto;
  width: 80%;
  text-align: left;
  margin-top: 10px;
  font-size: 13px;
}
.movie-msg-web ul li img {
  width: 80%;
  border-radius: 5px;
}
.movie-msg-pad {
  width: 100%;
}
.movie-msg-pad ul {
  list-style: none;
  margin: 0px;
  padding: 0px;
  margin-left: 10px;
  background-color: #ffffff;
  border-radius: 5px;
}
.movie-msg-pad ul li {
  text-align: center;
  padding: 10px;
}
.movie-msg-pad ul li div {
  margin: auto;
  width: 100%;
  text-align: left;
  font-size: 13px;
}
.movie-msg-pad ul li .movie-msg-infomation {
  width: 80%;
  margin: 0px;
  padding-left: 130px;
  line-height: 22px;
}
.movie-msg-pad ul li img {
  width: 120px;
  border-radius: 5px;
  max-height: 168px;
  float: left;
}

.movie-msg-phone {
  width: 100%;
}

.movie-msg-phone ul {
  list-style: none;
  margin: 0px;
  padding: 0px;
  margin-left: 10px;
  background-color: #ffffff;
  border-radius: 5px;
}
.movie-msg-phone ul li {
  text-align: center;
  padding: 10px;
}
.movie-msg-phone ul li div {
  margin: auto;
  width: 100%;
  text-align: left;
  font-size: 13px;
}
.movie-msg-phone ul li .movie-msg-infomation {
  width: 60%;
  margin: 0px;
  margin-left: 130px;
  line-height: 22px;
}
.movie-msg-phone ul li img {
  width: 120px;
  border-radius: 5px;
  max-height: 168px;
  float: left;
}

/*play-list*/
.play-list {
}
.play-list-web {
  position: absolute;
}

.play-list-web ul {
  list-style: none;
  margin: 0px;
  padding: 0px;
}
.play-list-web ul li {
  text-align: center;
}
.play-list-web ul li div {
  margin: auto;
  width: 90%;
  text-align: left;
  margin-top: 5px;
  font-size: 13px;
}
.play-list-web .vrmode{
  width: 55px;
  height: 35px;
  background-color: #409eff;
  text-align: center;
  line-height: 35px;
  color: #ffffff;
  margin-right: 5px;
  border-radius: 5px;
  cursor: pointer;
  float: left;
}
.play-list-web .play-index {
  width: 35px;
  height: 35px;
  background-color: #409eff;
  text-align: center;
  line-height: 35px;
  color: #ffffff;
  float: left;
  margin-right: 5px;
  border-radius: 5px;
  cursor: pointer;
}
.play-list-web .play-index-default {
  width: auto;
  padding-left: 10px;
  padding-right: 10px;
}
.play-list-web .selectActive {
  background-color: #ffffff;
  color: #409eff;
}

.play-list-pad {
  width: 100%;
  margin-bottom: 10px;
}

.play-list-pad ul {
  list-style: none;
  margin: 0px;
  padding: 0px;
  background-color: #ffffff;
  border-radius: 5px;
}
.play-list-pad ul li {
  text-align: center;
  padding: 10px;
}
.play-list-pad ul li div {
  margin: auto;
  width: 90%;
  text-align: left;
  margin: 0px;
  padding: 0px;
  font-size: 13px;
}
.play-list-pad .play-index {
  position: static;
  width: 35px;
  height: 35px;
  background-color: #409eff;
  text-align: center;
  line-height: 35px;
  color: #ffffff;
  float: left;
  margin-top: 10px;
  margin-right: 5px;
  border-radius: 5px;
  cursor: pointer;
}
.play-list-pad .play-index-default {
  width: auto;
  padding-left: 10px;
  padding-right: 10px;
}
.play-list-pad .selectActive {
  background-color: #ffffff;
  color: #409eff;
}

.play-list-phone {
  width: 100%;
  margin-bottom: 10px;
}

.play-list-phone ul {
  list-style: none;
  margin: 0px;
  padding: 0px;
  background-color: #ffffff;
  border-radius: 5px;
}
.play-list-phone ul li {
  text-align: center;
  padding: 10px;
}
.play-list-phone ul li div {
  margin: auto;
  width: 100%;
  text-align: left;
  margin: 0px;
  padding: 0px;
  font-size: 13px;
}
.play-list-phone .play-index {
  position: static;
  width: 30px;
  height: 30px;
  background-color: #409eff;
  text-align: center;
  line-height: 30px;
  color: #ffffff;
  float: left;
  margin-top: 10px;
  margin-right: 10px;
  border-radius: 5px;
  cursor: pointer;
}
.play-list-phone .play-index-default {
  width: auto;
  padding-left: 10px;
  padding-right: 10px;
}
.play-list-phone .selectActive {
  background-color: #ffffff;
  color: #409eff;
}
.clear {
  clear: both;
}
/*container*/
.container {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  clear: both;
  background-color: hsl(0, 0%, 96%);
  width: 100%;
  overflow-y: auto;
  text-align: center;
}
.container::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.container::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 20px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #535353;
}
.container::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  background: #ededed;
}
</style>